package xyz.xxin.xat.utils;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;

import androidx.core.app.ActivityCompat;

public class PermissionUtils {

    public static final int WRITE_EXTERNAL_STORAGE_CODE = 10001;
    public static final int ACCESS_FINE_LOCATION_CODE = 10002;
    public static final int ACCESS_COARSE_LOCATION_CODE = 10002;
    public static final int READ_PHONE_STATE_CODE = 10003;

    /**
     * 是否拥有读取手机状态权限
     */
    public static boolean isReadPhoneState(Context context){
        return ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED;
    }

    /**
     * 请求读取手机状态权限
     */
    public static void requestReadPhoneState(Activity activity){
        ActivityCompat.requestPermissions(activity, new String[] {
                Manifest.permission.READ_PHONE_STATE
        }, READ_PHONE_STATE_CODE);
    }

    /**
     * 是否拥有精准定位权限
     */
    public static boolean isFineLocation(Context context){
        return ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
    }

    /**
     * 请求精准定位权限
     */
    public static void requestFineLocation(Activity activity){
        ActivityCompat.requestPermissions(activity, new String[] {
                Manifest.permission.ACCESS_FINE_LOCATION
        }, ACCESS_FINE_LOCATION_CODE);
    }

    /**
     * 是否拥有粗略定位权限
     */
    public static boolean isCoarseLocation(Context context){
        return ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
    }

    /**
     * 请求粗略定位权限
     */
    public static void requestCoarseLocation(Activity activity){
        ActivityCompat.requestPermissions(activity, new String[] {
                Manifest.permission.ACCESS_COARSE_LOCATION
        }, ACCESS_COARSE_LOCATION_CODE);
    }

    /**
     * 是否拥有储存权限
     */
    public static boolean isWrite(Context context){
        boolean isRead = ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
        boolean isWrite = ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
        return (isRead && isWrite);
    }

    /**
     * 请求储存权限
     * @param activity 上下文
     */
    public static void requestWrite(Activity activity){
        ActivityCompat.requestPermissions(activity, new String[] {
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        }, WRITE_EXTERNAL_STORAGE_CODE);
    }
}
